package com.ruoyi.common.utils.excl.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.afterturn.easypoi.exception.excel.ExcelExportException;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.google.common.collect.Lists;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.GlobalAbstract;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.excl.ExcelImportBaseTemplate;
import com.ruoyi.common.utils.excl.model.ExcelCreateModel;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

/**
 * Excel导入导出工具类
 *
 * @author laoz
 */
@Slf4j
public class ExcelUtils
{

    /**
     * 从excel文件中读取多张sheet的值
     */
    public static <T> Map<String, List<T>> importExcelMultiple(MultipartFile file, Class<T> pojoClass, ImportParams params)
    {
        params.setTitleRows(1);
        params.setHeadRows(1);
        return baseImportExcelMultiple(file, pojoClass, params);
    }

    /**
     * 从excel文件中读取多张sheet的值
     */
    public static <T> Map<String, List<T>> baseImportExcelMultiple(MultipartFile file, Class<T> pojoClass, ImportParams params)
    {
        try {
            return new CExcelImportService().importExcelMultiple(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            throw new GlobalException("Excel表格数据读取失败");
        }
    }

    /**
     * 创建excel的workbook实体类
     * <p>
     * cn.afterturn.easypoi.excel.export.ExcelExportService#insertDataToSheet(org.apache.poi.ss.usermodel.Workbook, cn.afterturn.easypoi.excel.entity.ExportParams, java.util.List, java.util.Collection, org.apache.poi.ss.usermodel.Sheet)
     * 方法中 its.remove(); 每设置一行数值会删除列表中的信息，所以这里不能使用常量进行初始化复制
     * </p>
     *
     * @param modelList 模型列表
     */
    public static Workbook createExcelWorkbookMultipleSheet(List<ExcelCreateModel> modelList)
    {
        Workbook workbook = new HSSFWorkbook();
        ExcelExportService excelExportService = new ExcelExportService();
        for (ExcelCreateModel model : modelList) {
            excelExportService.createSheet(workbook,
                    new ExportParams(model.getTitle(), model.getSheetName()), model.getPojoClass(), model.getList());
        }
        return workbook;
    }

    /**
     * 创建excel的workbook实体类
     *
     * @param list      数据列表
     * @param title     表格标题
     * @param sheetName 子表名称
     * @param pojoClass 实体类类型
     * @return excel的workbook实体类
     */
    public static Workbook createExcelWorkbook(List<?> list, String title, String sheetName, Class<?> pojoClass)
    {
        return ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, list);
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response)
    {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response)
    {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
    {
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams)
    {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName,
                response,
                workbook);
    }

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
    {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new ExcelExportException(e.getMessage());
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
    {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) return;
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass)
    {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new ExcelExportException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExcelExportException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)
    {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new ExcelExportException("excel文件不能为空");
        } catch (Exception e) {
            throw new ExcelExportException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass, Integer keyIndex)
    {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setKeyIndex(keyIndex);
        List<T> list;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            throw new GlobalException("文件读取失败");
        }
        return list;
    }

    public static <T> List<T> importEasyExcel(MultipartFile file, Class<T> pojoClass, ReadListener<T> listen) throws IOException {
        if (file == null) {
            return null;
        }
        return EasyExcel.read(file.getInputStream(), listen).head(pojoClass).sheet().doReadSync();
    }

    public static <T> void exportEasyExcel(HttpServletResponse response, Class<T> pojoClass, List<T> resList, String sheetName) {
        try {
            //对应的导出实体类
            EasyExcel.write(response.getOutputStream(), pojoClass)
                    //excel文件类型，包括CSV、XLS、XLSX
                    .excelType(ExcelTypeEnum.XLSX)
                    //导出sheet页名称
                    .sheet(sheetName)
                    .doWrite(resList);
        } catch (IOException e) {
            // 应该打印log日志
            e.printStackTrace();
            throw new GlobalException("系统异常，文件导出失败");
        }
    }

    public static <T> List<T> importExcelRuoYi(MultipartFile file, Class<T> pojoClass, int titleNum)
    {
        if (file == null) {
            return null;
        }
        List<T> list;
        try {
            ExcelUtil<T> excelUtil = new ExcelUtil<>(pojoClass);
            list = excelUtil.importExcel(file.getInputStream(), titleNum);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("文件读取失败");
        }
        return list;
    }

    /**
     * 生成下载模板
     * @param response
     * @param pojoClass
     * @param baseTemplate
     * @param <T>
     */
    public static <T> void downloadExcelTemplateRuoYi(HttpServletResponse response, Class<T> pojoClass, ExcelImportBaseTemplate baseTemplate)
    {
        Workbook workbook = null;
        try {
            ExcelUtil<T> excelUtil = new ExcelUtil<>(pojoClass);
            fullDropdown(pojoClass);
            workbook = excelUtil.generateExcelTemplate(response, baseTemplate);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成模板异常{}", e.getMessage());
            throw new GlobalException("模板生成失败");
        } finally {
            IOUtils.closeQuietly(workbook);
        }
    }

    public static <T> void exportExcelRuoYi(HttpServletResponse response, List<T> list, Class<T> pojoClass, String title, String sheetName)
    {
        try {
            ExcelUtil<T> excelUtil = new ExcelUtil<>(pojoClass);
            excelUtil.exportExcel(response, list, sheetName, title);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("文件导入失败");
        }
    }

    /**
     * 填充下拉框值列表
     * @param pojoClass
     */
    private static <T> void fullDropdown(Class<T> pojoClass) {
        Field[] fields = ReflectUtil.getFields(pojoClass);
        for (Field field : fields) {
            field.setAccessible(true);
            Object customDictTypeValue = AnnotationUtil.getAnnotationValue(field, Excel.class, "customDictType");
            if (ObjectUtil.isEmpty(customDictTypeValue)) {
                continue;
            }
            Map<Long, String> customerValuesMap;
            // 该属性值表示商品列表,对其特殊处理
            if (Constants.GOODS_SKU_CODE.equals(customDictTypeValue.toString())) {
                customerValuesMap = SpringUtils.getBean(GlobalAbstract.class).cacheParentGoodsMap();
            } else {
                customerValuesMap = SpringUtils.getBean(GlobalAbstract.class).cacheDictParentMap(Lists.newArrayList(customDictTypeValue.toString()));
            }
            if (CollectionUtil.isNotEmpty(customerValuesMap)) {
                Collection<String> values = customerValuesMap.values();
                Object isFilterStr = AnnotationUtil.getAnnotationValue(field, Excel.class, "needFilterStr");
                if (ObjectUtil.isNotEmpty(isFilterStr)) {
                    values = values.stream().filter(s -> StrUtil.contains(s, StrUtil.DASHED)).collect(Collectors.toList());
                }
                Excel annotation = AnnotationUtil.getAnnotation(field, Excel.class);
                modifyAnnotation(annotation, "combo", values.toArray(new String[0]));
            }
        }
    }


    /**
     * 修改Excel注解的指定字段值
     * 此方法通过反射和动态代理修改注解实例的字段值，以便在运行时更改注解的行为
     *
     * @param annotation     要修改的Excel注解实例
     * @param annotationFieldName  注解字段名称，指定需要修改的字段
     * @param newValue           新的字段值，用于替换原有字段值
     */
    private static void modifyAnnotation(Excel annotation, String annotationFieldName, Object newValue)  {
        try {
            InvocationHandler handler = Proxy.getInvocationHandler(annotation);
            Field memberValues = handler.getClass().getDeclaredField("memberValues");
            memberValues.setAccessible(true);
            Map<String, Object> values = (Map<String, Object>) memberValues.get(handler);
            values.put(annotationFieldName, newValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
